package com.permissiionx.androidthreadtest

import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.concurrent.thread
import android.app.ProgressDialog
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.*
import android.widget.ProgressBar
import android.widget.Toast
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.MalformedURLException
import java.net.URL
import java.net.URLConnection


class MainActivity : AppCompatActivity() {
    val updateText = 1
    private val progress: ProgressDialog? = null

    //val url :Unit = "http://img-s-msn-com.akamaized.net/tenant/amp/entityid/AARpNBb.img"
    val url = arrayOf("http://img-s-msn-com.akamaized.net/tenant/amp/entityid/AARpNBb.img"
                ,"http://img-s-msn-com.akamaized.net/tenant/amp/entityid/AARpNBb.img")
    //val url1:Unit = (object)(url)

    val handler = object: Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            //在这里可以进行UI操作
           when(msg.what){
               updateText -> textView.text = "Nice to meet you"
           }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)



        changeTextBtn.setOnClickListener{
            thread{
                //textView.text = "Nice to meet you"
                val msg = Message()
                msg.what = updateText
                handler.sendMessage(msg)//将Message对象发送出去
            }
        }

        downloadtBtn.setOnClickListener{
            DownloadTask().execute()
            progressBar.progress = progressBar.progress + 1
        }
    }

    //内部类
    inner class DownloadTask : AsyncTask<Unit, Int, Boolean>() {

        override fun onPreExecute() {

        }

//    override fun doInBackground(vararg params: Unit?) = try {
//        while (true) {
//            val downloadPercent = doDownload()//这是一个虚构的方法
//            publishProgress(downloadPercent)
//            if (downloadPercent >= 100) {
//                break
//            }
//        }
//        true
//    }catch (e:Exception){
//        false
//    }

        override  fun doInBackground(vararg params: Unit?): Boolean? {
            // TODO Auto-generated method stub
            //params是一个可变长的数组 在这里我们只传进来了一个url
            val url = "https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AARpNBb.img"
            var bitmap: Bitmap? = null
            val connection: URLConnection
            val `is`: InputStream //用于获取数据的输入流
            val bos: ByteArrayOutputStream //可以捕获内存缓冲区的数据，转换成字节数组。
            var len: Int
            var count = 0f
            val total: Float //count为图片已经下载的大小 total为总大小
            try {
                //获取网络连接对象
                //https://scx-white.blog.csdn.net/article/details/50759618?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-1.no_search_link
                connection = URL(url.toString()).openConnection() as URLConnection
                //获取当前页面的总长度
                total = connection.getContentLength().toFloat()
                //获取输入流
                `is` = connection.getInputStream()
                bos = ByteArrayOutputStream()
                val data = ByteArray(1024)
                while (`is`.read(data).also { len = it } != -1) {
                    count += len.toFloat()
                    bos.write(data, 0, len)
                    //调用publishProgress公布进度,最后onProgressUpdate方法将被执行
                    publishProgress((count / total * 100).toInt())
                    //为了显示出进度 人为休眠0.5秒
                    Thread.sleep(500)
                }
                bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.toByteArray().size)
                `is`.close()
                bos.close()
            } catch (e: MalformedURLException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            } catch (e: IOException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            } catch (e: InterruptedException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }
            return true
        }

        override fun onProgressUpdate(vararg values: Int?) {
            //在这里更新下载进度
            progressBar?.progress = values[0]!!
            Log.d("Main", progressBar?.progress.toString())
        }
        override fun onPostExecute(result: Boolean) {
           // progressDialog?.dismiss()//关闭进度对话框
            //在这里提示下载结果
            if(result){
                Toast.makeText(MyApplication.context,"DownLoad succeeded", Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(MyApplication.context, "DownLoad failed", Toast.LENGTH_SHORT).show()
            }
        }

        //模拟下载任务
        fun doDownload() :Int{
            var result:Int = 1
            for(i in 1..100 step 2)
            {
                // Thread.sleep(1000)
                result = i
            }
            return result
        }
    }
}